package shoozhoo.libandrotranslation;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class TranslationListActivity extends ListActivity {
	public static final String INTENT_EXTRA_MAIL_APPNAME = "INTENT_EXTRA_MAIL_APPNAME";
	public static final String INTENT_EXTRA_MAIL_TO = "INTENT_EXTRA_MAIL_TO";
	public static final String INTENT_EXTRA_PACKAGE = "INTENT_EXTRA_PACKAGE";
	public static final String INTENT_EXTRA_DIR = "INTENT_EXTRA_DIR";
	public static final String INTENT_EXTRA_SHOW_LIBANDROTRANSLATION_RESOURCE = "INTENT_EXTRA_SHOW_LIBANDROTRANSLATION_RESOURCE";
	public static final String INTENT_EXTRA_IGNORE_PATTERNS = "INTENT_EXTRA_IGNORE_PATTERNS";
	public static final int REQUEST_EDIT = 100;
	public static final int REQUEST_MAIL = 200;

	private Handler handler = new Handler();
	private List<String> pkgs;
	private StringResources strReses;
	private List<StringRes> resList;
	private TextView rateTextView;
	private Spinner langSpinner;
	private String lang;
	private boolean showSelfResource;
	private String dir;
	private String mailApp;
	private String mailTo;
	private List<String> ignorePattern;

	private boolean initialized;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.libandrotranslation_translation);

		Intent intent = getIntent();
		this.showSelfResource = intent.getBooleanExtra(INTENT_EXTRA_SHOW_LIBANDROTRANSLATION_RESOURCE, false);
		this.dir = intent.getStringExtra(INTENT_EXTRA_DIR);
		this.mailApp = intent.getStringExtra(INTENT_EXTRA_MAIL_APPNAME);
		this.mailTo = intent.getStringExtra(INTENT_EXTRA_MAIL_TO);
		this.ignorePattern = intent.getStringArrayListExtra(INTENT_EXTRA_IGNORE_PATTERNS);
		for (String s : ignorePattern) {
			System.out.println("## "+s);
		}
		this.pkgs = new ArrayList<String>();
		try{
			String s = intent.getStringExtra(INTENT_EXTRA_PACKAGE);
			if(s!=null){
				pkgs.add(s);
			}
		}catch (Throwable e) {}
		if(pkgs.isEmpty()){
			pkgs.add(getApplication().getPackageName());
		}

		this.lang = LibAndTransUtil.getTranslationLang(this);
		if(this.lang==null){
			this.lang="";
		}
		this.rateTextView = (TextView)findViewById(R.id.rate_text);

		this.langSpinner = (Spinner)findViewById(R.id.lang_spinner);
		{
			String[] codes = getResources().getStringArray(R.array.libandrotranslation_lang_entries_value);
			for(int i=0; i<codes.length; i++){
				if(lang.startsWith(codes[i])){
					this.langSpinner.setSelection(i);
					break;
				}
			}
		}
		this.langSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> adView, View view,
					int pos, long id) {
				TranslationListActivity.this.lang = getResources().getStringArray(R.array.libandrotranslation_lang_entries_value)[langSpinner.getSelectedItemPosition()];
				LibAndTransUtil.saveTranslationLang(TranslationListActivity.this, TranslationListActivity.this.lang);
			}

			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();
		refresh();
		if(!initialized){
			initialDialog();
		}
		initialized=true;
	}
	private void initialDialog(){
		for (StringRes res : this.resList) {
			String s = res.getUserString();
			if(s!=null && !s.equals("") && !s.equals("\\s+")){
				// When the user translation exists, it doesn't display.
				return;
			}
		}
		new AlertDialog.Builder(this)
		.setMessage(R.string.zzlibandrotranslation_list_first_msg)
		.setPositiveButton(android.R.string.ok, null)
		.create().show();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		StringRes res = this.resList.get(position);
		Intent i = new Intent(this, TranslationEditActivity.class);
		i.putExtra(TranslationEditActivity.INTENT_EXTRA_STRING_RES, res);
		i.putExtra(TranslationEditActivity.INTENT_EXTRA_LANG, this.lang);
		startActivityForResult(i, REQUEST_EDIT);
	}


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		System.out.println("onActivityResult "+requestCode+"/"+resultCode);
		if(resultCode!=RESULT_OK){
			return;
		}
		switch(requestCode){
		case REQUEST_EDIT:
			onEdit(data);
			break;
		case REQUEST_MAIL:
			break;
		}
	}
	private void onEdit(Intent data){
		StringRes res = data.getParcelableExtra(TranslationEditActivity.INTENT_EXTRA_STRING_RES);
		this.strReses.updateStringResource(res);
		try{
			this.strReses.saveUserResource(this);
		}catch (Exception e) {
			errorToast(R.string.zzlibandrotranslation_toast_cant_write_resource);
			LibAndTransUtil.log(e.getMessage());
			e.printStackTrace();
			return;
		}
		this.refresh();
	}

	/*
	 * Menu
	 */
	private static final int MENU_SEND_MAIL = Menu.FIRST + 1;
	private static final int MENU_ALL_CLEAR = MENU_SEND_MAIL + 1;
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.clear();
		menu.add(0, MENU_SEND_MAIL, 1, R.string.zzlibandrotranslation_list_menu_send_mail).setIcon(R.drawable.libandrotranslation_ic_menu_send);
		menu.add(0, MENU_ALL_CLEAR, 2, R.string.zzlibandrotranslation_list_menu_all_clear).setIcon(R.drawable.libandrotranslation_ic_menu_close_clear_cancel);
		return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case MENU_SEND_MAIL:
			sendMail();
			break;
		case MENU_ALL_CLEAR:
			userTranslationAllClear();
			break;
		}
		return true;
	}

	/*
	 * Send mail
	 */
	private void sendMail(){
		Intent intent = new Intent();
		if(this.pkgs.size()==1){
			intent.setAction(Intent.ACTION_SEND);
		}else{
			intent.setAction(Intent.ACTION_SEND_MULTIPLE);
		}
		intent.putExtra(Intent.EXTRA_EMAIL, new String[]{mailTo});
		intent.putExtra(Intent.EXTRA_SUBJECT, mailSubject());
		intent.putExtra(Intent.EXTRA_TEXT, mailContent());
		intent.setType("text/plain");
		if(this.pkgs.size()==1){
			Uri uri = this.strReses.getTranslationXmlFile(this, this.pkgs.get(0));
			System.out.println("Attach "+uri);
			intent.putExtra(Intent.EXTRA_STREAM, uri);
		}else{
			ArrayList<Uri> uris = new ArrayList<Uri>();
			for(int i=0; i<this.pkgs.size(); i++){
				uris.add(this.strReses.getTranslationXmlFile(this, this.pkgs.get(i)));
			}
			intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
		}
		try{
			startActivityForResult(Intent.createChooser(intent,null), REQUEST_MAIL);
		}catch (Exception e) {
			errorToast(R.string.zzlibandrotranslation_list_mailer_not_found);
		}
	}


	private String mailSubject(){
		// It doesn't internationalize.
		// The developer is sure to know English.
		return "[" + this.mailApp + "] Translation Request (Language: "+ this.lang +" / "+Locale.getDefault()+")";
	}

	private String mailContent(){
		// It doesn't internationalize.
		// The developer is sure to know English.
		return "Translation request.";
	}

	/*
	 * All clear
	 */
	private void userTranslationAllClear(){
		new AlertDialog.Builder(this)
		.setMessage(R.string.zzlibandrotranslation_list_all_clear_confirm)
		.setPositiveButton(android.R.string.ok, new OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				TranslationListActivity.this.strReses.clear();
				try{
					TranslationListActivity.this.strReses.saveUserResource(TranslationListActivity.this);
				}catch (Exception e) {
					LibAndTransUtil.log("save error",e);
				}
				TranslationListActivity.this.refresh();
			}
		})
		.setNegativeButton(android.R.string.cancel, null)
		.create().show();
	}

	/*
	 * List update
	 */
	private void refresh(){
		this.strReses = new StringResources(pkgs);
		this.strReses.setIgnoreSelfResource(!showSelfResource);
		this.strReses.setIgnorePatterns(this.ignorePattern);
		if(dir!=null){
			this.strReses.setDir(dir);
		}
		try{
			this.strReses.loadStringResources(getApplicationContext());
		}catch (Exception e) {
			errorToast(R.string.zzlibandrotranslation_toast_cant_read_resource);
			LibAndTransUtil.log(e.getMessage());
			e.printStackTrace();
			return;
		}
		this.resList = this.strReses.getStringResources();

		// TODO I don't want to move the position of the list.
//		int position = 0;
//		int positionY = 0;
//		if(getListView().getChildCount()>0){
//			position = getListView().getFirstVisiblePosition();
//			positionY = getListView().getChildAt(0).getTop();
//		}
		setListAdapter(new TranslationAdapter(TranslationListActivity.this, 0, this.resList.toArray(new StringRes[0])));
//		final int p = position;
//		final int py = positionY;
//		handler.postDelayed(new Runnable() {
//			public void run() {
//				getListView().setSelectionFromTop(p, py);
//			}
//		},1);

		this.upateRateTextView();
	}
	private void upateRateTextView(){
		int sum = this.resList.size();
		int translated = 0;
		for (StringRes res : this.resList) {
			String s = res.getUserString();
			if(s!=null && !s.equals("") && !s.matches("\\s+")){
				translated++;
			}
		}
		this.rateTextView.setText(translated+" / "+sum);
	}

	/*
	 * error toast and finish
	 */
	private void errorToast(final int res){
		handler.post(new Runnable() {
			public void run() {
				Toast.makeText(TranslationListActivity.this, res, Toast.LENGTH_LONG).show();
				finish();
			}
		});
	}

	private class TranslationAdapter extends ArrayAdapter<StringRes>{
		private LayoutInflater inflater;

		public TranslationAdapter(Context ctx, int res, StringRes[] reses){
			super(ctx, res, reses);
			this.inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if(convertView==null){
				convertView = this.inflater.inflate(R.layout.libandrotranslation_translation_row, null);
			}
			final StringRes res = this.getItem(position);
			if(res==null){
				return convertView;
			}
			TextView label = (TextView)convertView.findViewById(R.id.row_label);
			TextView defTv = (TextView)convertView.findViewById(R.id.def_string);
			TextView userTv = (TextView)convertView.findViewById(R.id.user_string);
			defTv.setText(res.getDefString());
			userTv.setText(res.getUserString());
			if(res.getUserString()==null || res.getUserString().matches("\\s*")){
				label.setBackgroundColor(Color.GRAY);
			}else{
				label.setBackgroundColor(Color.GREEN);
			}

			return convertView;
		}
	}
}